package com.lbw.Server.ratelimit.impl;


import com.lbw.Server.ratelimit.RateLimit;

/**
 * @author lbwxxc
 * @date 2025/2/23 10:34
 * @description: TODO
 */
public class TokenBucketRateLimitImpl implements RateLimit {
    //令牌产生速率（单位为ms）
    private static  int RATE;
    //桶容量
    private static  int CAPACITY;
    //当前桶容量
    private volatile int curCapacity;
    //时间戳
    private volatile long timeStamp=System.currentTimeMillis();

    public TokenBucketRateLimitImpl(int rate, int curCapacity) {
        this.RATE = rate;
        this.CAPACITY = curCapacity;
        this.curCapacity = curCapacity;
    }

    @Override
    public synchronized boolean getToken() {
        if (curCapacity > 0) {
            System.out.println("TokenBucketRateLimitImpl.getToken() 限流通过");
            curCapacity--;
            return true;
        }
        long current = System.currentTimeMillis();
        if ((current - timeStamp) >= RATE) {
            if ( (current - timeStamp) >= 2) {
                curCapacity = (int)(current - timeStamp) / RATE - 1;
            }
            if (curCapacity > CAPACITY) {
                curCapacity = CAPACITY;
            }

            timeStamp = current;
            return true;
        }
        return false;
    }

}
